import { _decorator, Component, Node } from 'cc';
import { CallBackHandler } from '../../Basic/Model/PoolObj/CallBackHandler';
const { ccclass } = _decorator;

@ccclass('MouseCtrl')
export class MouseCtrl extends Component {
  touchStartTimer = this.onTouchStart.bind(this);
  touchMoveTimer = this.onTouchMove.bind(this);
  touchEndTimer = this.onTouchEnd.bind(this);

  touchStartCallback: CallBackHandler;
  touchMoveCallback: CallBackHandler;
  touchEndCallback: CallBackHandler;

  protected onLoad(): void {
    this.touchStartCallback = null;
    this.touchMoveCallback = null;
    this.touchEndCallback = null;
    this.node.on(Node.EventType.TOUCH_START, this.touchStartTimer);
  }

  /** 注册触控函数
   * @param tsc 按下回调
   * @param tmc 拖拽回调
   * @param tec 抬起回调
   */
  registEvent(tsc?: CallBackHandler, tmc?: CallBackHandler, tec?: CallBackHandler) {
    this.touchStartCallback = tsc;
    this.touchMoveCallback = tmc;
    this.touchEndCallback = tec;
  }

  resetEvent() {
    this.touchStartCallback = null;
    this.touchMoveCallback = null;
    this.touchEndCallback = null;
  }

  onTouchStart(t: TouchEvent) {
    if (this.touchStartCallback != null) this.touchStartCallback.activate(t);
    if (this.touchMoveCallback != null) this.node.on(Node.EventType.TOUCH_MOVE, this.touchMoveTimer);
    this.node.on(Node.EventType.TOUCH_END, this.touchEndTimer);
  }

  onTouchMove(t: TouchEvent) {
    if (this.touchMoveCallback != null) this.touchMoveCallback.activate(t);
  }

  onTouchEnd(t: TouchEvent) {
    this.node.off(Node.EventType.TOUCH_MOVE, this.touchMoveTimer);
    this.node.off(Node.EventType.TOUCH_END, this.touchEndTimer);
    if (this.touchEndCallback != null) this.touchEndCallback.activate(t);
  }
}
